package com.tron.dobest.java.tronnio;


import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

public class TronScatterAndGather {
    public static void main(String[] args) {
        try {
            //建立服务器
            final ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            //绑定端口
            serverSocketChannel.socket().bind(new InetSocketAddress(6666));
            final ByteBuffer[] byteBuffers = new ByteBuffer[2];
            byteBuffers[0] = ByteBuffer.allocate(1);
            byteBuffers[1] = ByteBuffer.allocate(4);
            //等待连接
            final SocketChannel socketChannel = serverSocketChannel.accept();
            //读取数据
            while (true) {
                //读取数据
                socketChannel.read(byteBuffers);
                Arrays.asList(byteBuffers).stream().map(e->"position="+e.position()+", limit="+e.limit())
                        .forEach(System.out::println);
                Arrays.asList(byteBuffers).stream().forEach(e->e.flip());
                //回写数据
                socketChannel.write(byteBuffers);
                Arrays.asList(byteBuffers).stream().forEach(e->e.clear());
            }


        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
